package com.ali.common;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

public class AesUtil {
    private static final String AES = "AES";
    private static final String AES_CBC = "AES/CBC/PKCS5Padding";

    /**
     * AES加密
     */
    public static String encrypt(String content, String key) {
        byte[] contentByte = content.getBytes(StandardCharsets.UTF_8);

        try {
            Cipher cipher = getCipher(key, Cipher.ENCRYPT_MODE);
            byte[] doFinalByte = cipher.doFinal(contentByte);
            return Base64Util.encrypt(doFinalByte);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取Cipher
     */
    private static Cipher getCipher(String key, int opmode) {
        byte[] keyByte = key.getBytes(StandardCharsets.UTF_8);

        try {
            Cipher cipher = Cipher.getInstance(AES_CBC);
            SecretKeySpec secretKeySpec = new SecretKeySpec(keyByte, AES);
            IvParameterSpec ivParameterSpec = new IvParameterSpec(keyByte);
            cipher.init(opmode, secretKeySpec, ivParameterSpec);
            return cipher;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * AES解密
     */
    public static String decrypt(String encryptStr, String key) {
        try {
            byte[] encryptStrByte = Base64Util.getByteByDecrypt(encryptStr);

            Cipher cipher = getCipher(key, Cipher.DECRYPT_MODE);
            byte[] doFinalByte = cipher.doFinal(encryptStrByte);
            return new String(doFinalByte, StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}